package com.example.demo.controller;


import com.example.demo.constant.ErrorCode;
import com.example.demo.entity.AreaInfo;
import com.example.demo.result.Result;
import com.example.demo.service.QueryService;
import lombok.AllArgsConstructor;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;


@RestController

@AllArgsConstructor
public class QueryController {

    private final QueryService queryService;

    private final CacheManager cacheManager;

    @GetMapping("/query/{phone}")
    public Result<AreaInfo> search(@PathVariable String  phone) {
        if (phone.length()!=11){
            return Result.error(ErrorCode.BODY_NOT_MATCH);
        }

        return Result.success(queryService.query(phone));

    }

    @GetMapping("/query")

    public Result<String> queryHead(String s){
        if(s.length()<3){
            return Result.error(ErrorCode.BODY_NOT_MATCH);
        }
        Cache cache = cacheManager.getCache("queryHead");
        String ss = s.substring(0,3);

        Cache.ValueWrapper cached = cache.get(ss);

        //  命中缓存直接返回
        if(cached != null) {

            return Result.success((String)cached.get());
        }else {
            // 未命中缓存，查询
            AreaInfo query = queryService.query(ss + "88888888");
            cache.put(ss,query.getSp());
        }



        return Result.error(ErrorCode.SIGNATURE_NOT_MATCH);

    }
}
